package net.danielpaz.pucc.poo.trabalho.model;

/**
 * Classe para manipular dados de objetos da classe Local no banco de dados
 * @author Guilherme
 * @date 14/06/2014
 *
 */

import java.sql.*;

public class LocalDAO {

	public Local loc;
	public Conexao bd;
	private PreparedStatement statement;
	private ResultSet resultSet;
	private String men, sql;
	public static final byte INCLUSAO = 1;
	public static final byte ALTERACAO = 2;
	public static final byte EXCLUSAO = 3;

	public LocalDAO() {
		bd = new Conexao();
		loc = new Local();
		bd.getConnection();
	}

	public boolean localizar(int id) {

		sql = "SELECT * FROM LOCAL WHERE ID = ?";

		try {

			System.out.println(sql);

			statement = bd.connection.prepareStatement(sql);
			statement.setInt(1, id);
			resultSet = statement.executeQuery();

			while (resultSet.next()) {
				loc.setId(Integer.parseInt(resultSet.getString(1)));
				loc.setNome(resultSet.getString(2));
			}
			return true;
		} catch (Exception erro) {
			erro.printStackTrace();
			System.out.println(erro.getMessage());
			return false;
		}
	}

	public String atualizar(int operacao) {

		men = "Operacao realizada com sucesso!";

		try {
			if (operacao == INCLUSAO) { 
				sql = "INSERT INTO LOCAL VALUES (?)";
				statement = bd.connection.prepareStatement(sql);
				
				/*
				 * Caso o campo ID da tabela seja auto-increment, apagar esta linha
				 * statement.setString(1, "" + loc.getId());
				 */
				
				statement.setString(1, "" + loc.getNome());
			} else if (operacao == ALTERACAO) {
				sql = "UPDATE LOCAL SET NOME = ? WHERE ID = ?";
				statement = bd.connection.prepareStatement(sql);
				statement.setString(1, "" + loc.getNome());
				statement.setString(2, "" + loc.getId());

			} else if (operacao == EXCLUSAO) {
				sql = "DELETE FROM LOCAL WHERE ID = ?";
				statement = bd.connection.prepareStatement(sql);
				statement.setString(1, "" + loc.getId());
			}
			if (statement.executeUpdate() == 0)
				men = "Falha na operacao!";
		} catch (SQLException erro) {
			men = "Falha na operacao " + erro.toString();
		}
		return men;
	}
}
